<template>
  <div class="database-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据库管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加数据库
          </el-button>
        </div>
      </template>

      <!-- 数据库列表 -->
      <el-table :data="databaseList" border style="width: 100%">
        <el-table-column prop="index" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="名称" />
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="序号" prop="index">
          <el-input-number 
            v-model="formData.index" 
            :min="1" 
            style="width: 100%"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入数据库名称" />
        </el-form-item>
        <el-form-item label="数据库名" prop="databaseName">
          <el-input v-model="formData.databaseName" placeholder="请输入数据库名" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ip">
          <el-input v-model="formData.ip" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input-number 
            v-model="formData.port" 
            :min="1" 
            :max="65535"
            style="width: 100%"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="formData.password" 
            type="password" 
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="handleSave">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { testDatabaseConnection, addDatabase, updateDatabase, deleteDatabase, getDatabaseList } from '@/api/database'

interface DatabaseItem {
  id?: number
  index: number
  name: string
  databaseName: string
  ip: string
  port: number
  username: string
  password: string
}

// 数据库列表
const databaseList = ref<DatabaseItem[]>([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加数据库')
const formRef = ref<FormInstance>()
const saveLoading = ref(false)
const isEdit = ref(false)
const currentId = ref<number>()

// 表单数据
const formData = reactive<DatabaseItem>({
  index: 1,
  name: '',
  databaseName: '',
  ip: '',
  port: 1433,
  username: '',
  password: ''
})

// 表单验证规则
const rules: FormRules = {
  index: [{ required: true, message: '请输入序号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  databaseName: [{ required: true, message: '请输入数据库名', trigger: 'blur' }],
  ip: [
    { required: true, message: '请输入IP地址', trigger: 'blur' },
    { pattern: /^(\d{1,3}\.){3}\d{1,3}$/, message: 'IP地址格式不正确', trigger: 'blur' }
  ],
  port: [{ required: true, message: '请输入端口', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 重置表单
const resetForm = () => {
  formData.index = 1
  formData.name = ''
  formData.databaseName = ''
  formData.ip = ''
  formData.port = 1433
  formData.username = ''
  formData.password = ''
  formRef.value?.clearValidate()
}

// 添加
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加数据库'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: DatabaseItem) => {
  isEdit.value = true
  currentId.value = row.id
  dialogTitle.value = '编辑数据库'
  
  formData.index = row.index
  formData.name = row.name
  formData.databaseName = row.databaseName
  formData.ip = row.ip
  formData.port = row.port
  formData.username = row.username
  formData.password = row.password
  
  dialogVisible.value = true
}

// 保存
const handleSave = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      
      try {
        // 先测试数据库连接
        const testResult = await testDatabaseConnection({
          databaseName: formData.databaseName,
          ip: formData.ip,
          port: formData.port,
          username: formData.username,
          password: formData.password
        })
        
        if (testResult.success) {
          // 连接成功，保存数据
          if (isEdit.value) {
            await updateDatabase(currentId.value!, formData)
            ElMessage.success('修改成功')
          } else {
            await addDatabase(formData)
            ElMessage.success('添加成功')
          }
          
          dialogVisible.value = false
          loadDatabaseList()
        } else {
          ElMessage.error('数据库连接失败，请检查配置信息')
        }
      } catch (error) {
        ElMessage.error('数据库连接失败，请检查配置信息')
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 删除
const handleDelete = (row: DatabaseItem) => {
  ElMessageBox.confirm('确定要删除该数据库配置吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteDatabase(row.id!)
    ElMessage.success('删除成功')
    loadDatabaseList()
  }).catch(() => {})
}

// 加载数据库列表
const loadDatabaseList = async () => {
  try {
    const res = await getDatabaseList()
    if (res.success && res.data) {
      databaseList.value = res.data
    }
  } catch (error) {
    console.error('加载数据库列表失败:', error)
    databaseList.value = []
  }
}

// 初始化
loadDatabaseList()
</script>

<style scoped>
.database-container {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

